<?php

namespace App\Http\ApiControllers;

use App\Models\Player;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Mews\Captcha\Facades\Captcha;

class AuthController extends ApiController
{
    /**
     * Notes   : 验证码
     *
     * @Date   : 2024/7/29 下午5:23
     * @Author : <Jason.C>
     * @param  Player  $player
     * @return JsonResponse
     */
    public function captcha(Player $player): JsonResponse
    {
        if ($player->season->config['show_captcha']) {
            return $this->success(Captcha::create($player->season->config['captcha_type'], true));
        } else {
            return $this->failed('未开启验证码');
        }
    }

    /**
     * Notes   : 获取登录地址
     *
     * @Date   : 2024/7/29 下午4:53
     * @Author : <Jason.C>
     * @param  Request  $request
     * @param  Player  $player
     * @return JsonResponse
     * @throws Exception
     */
    public function auth(Request $request, Player $player): JsonResponse
    {
        $base = [
            'app_key' => $request->application->app_key,
            'player_id' => $player->id,
            'callback' => $request->callback,
        ];
        ksort($base);
        $params = array_merge($base, [
            'app_secret' => $request->application->app_secret,
        ]);

        $signature = strtoupper(md5(http_build_query($params)));

        return $this->success(route('auth.wechat.token',
            array_merge($base, ['signature' => $signature])
        ));
    }
}
